import 'dart:async';
import 'package:bookshelf/socket/send_helper.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_libserialport/flutter_libserialport.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import '../entity/setting_entity.dart';
import '../event/inventory_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../util/toast_util.dart';
import 'log_page.dart';

class SettingCommon extends StatefulWidget {
  const SettingCommon({Key? key}) : super(key: key);

  @override
  State<SettingCommon> createState() => _SettingCommonState();
}

class _SettingCommonState extends State<SettingCommon>  {

  StreamSubscription? actionSubscription;
  SettingEntity? entity;
  final box = GetStorage();
  var _apiAddr = "192.168.2.100";
  var _deviceName = "图书馆";
  var _deviceNo = "device_id=rfid_bookshelf_0001";
  var _roomName = '轩毅体验区';
  var _psw = '000000';
  var _roomNo = '01';
  var _columnNo = '0001';
  var _auth = '1';
  // var _kdAppId = 'b75833186a37a7975af0dbb255750195';
  // var _kdAppSecret = '0b932941798cfb6b284e8af03cdee7ed';
  // var _kdEpId = '1';
  // var _kdApi = '10.113.1.11:18080';
  var _inventoryTime = 600;
  var _sleepTime = 60;
  var _actionTime = 120;
  var _rotate = 2;
  final _exchange = false.obs;
  final _log = false.obs;
  final _action = true.obs;
  final _idSerial = '/dev/ttyS1'.obs;
  final _hfSerial = '/dev/ttyS0'.obs;
  final _hfBaudRate = '115200'.obs;
  final _analysisBook = 'xy'.obs;
  final _analysisReader = 'xy'.obs;
  final _norms = '5层'.obs;
  // final _face = 'xy'.obs;

  final List<SettingEntityPlace> _placeList = RxList();
  final List<SettingEntityReader> _readerList = RxList();

  RxBool twoSided = true.obs;
  RxBool main = true.obs;


  final List<DropdownMenuItem> _baudRatedRules =
    [
      const DropdownMenuItem(value: '4800', child: Text('4800'),),
      const DropdownMenuItem(value: '9600', child: Text('9600'),),
      const DropdownMenuItem(value: '19200', child: Text('19200'),),
      const DropdownMenuItem(value: '38400', child: Text('38400'),),
      const DropdownMenuItem(value: '57600', child: Text('57600'),),
      const DropdownMenuItem(value: '115200', child: Text('115200'),),
    ];
  final List<DropdownMenuItem> _analysisBookRules =
    [
      const DropdownMenuItem(value: 'xy', child: Text('xy'),),
      const DropdownMenuItem(value: 'py', child: Text('py'),),
      const DropdownMenuItem(value: 'kd', child: Text('kd'),),
    ];
  final List<DropdownMenuItem> _analysisReaderRules =
    [
      const DropdownMenuItem(value: 'xy', child: Text('xy'),),
      const DropdownMenuItem(value: 'py', child: Text('py'),),
    ];
  final List<DropdownMenuItem> _normsRules =
    [
      const DropdownMenuItem(value: '5层', child: Text('5层'),),
      const DropdownMenuItem(value: '6层', child: Text('6层'),),
    ];

  @override
  initState() {
    super.initState();

    if(box.hasData('setting_entity')){
      entity = SettingEntity.fromJson(box.read("setting_entity"));
      _init();
    }else{
      entity = SettingEntity();
    }

    actionSubscription = eventFactory.on<InventoryEvent>().listen((event) {
      BotToast.closeAllLoading();

      // Map<int, int> map = {};
      //
      // var floor = 5;
      // if(_norms.value == '5层'){
      //   floor = 5;
      // }
      // if(_norms.value == '6层'){
      //   floor = 6;
      // }
      //
      // for(var i = 1;i<= floor*2;i++){
      //   map[i] = 0;
      // }
      // for (var element in event.data) {
      //   int ant = int.parse(element.$2,radix: 16);
      //   int count = map[ant]!;
      //   map[ant] = count+1;
      // }
      //
      // var text = '总数:${event.data.length}\n';
      // for(var i = 1;i<= floor*2;i++){
      //   text += '天线$i:${map[i]}\n';
      // }
      Get.defaultDialog(
        title: '盘点完成',
        titleStyle: TextStyle(
          color: const Color(0xFF000000),
          fontSize: 8.sp,
        ),
        middleText: '盘点到${event.data.length}个标签',
        middleTextStyle: TextStyle(
          color: const Color(0xFF000000),
          fontSize: 8.sp,
        ),
        radius: 8.sp,
        textConfirm: '确定',
        // textCancel: '取消',
        confirmTextColor: const Color(0xFF007AFF),
        backgroundColor: const Color(0xD1F8F8F8),
        buttonColor: Colors.transparent,
        onConfirm: () {
          Get.back();
        },
      );
    });
  }
  _init(){
    if(entity!.apiAddr != null){
      _apiAddr = entity!.apiAddr!;
    }
    if(entity!.deviceNo != null){
      _deviceNo = entity!.deviceNo!;
    }
    // if(entity!.kdAppId != null){
    //   _kdAppId = entity!.kdAppId!;
    // }
    // if(entity!.kdAppSecret != null){
    //   _kdAppSecret = entity!.kdAppSecret!;
    // }
    // if(entity!.kdEpId != null){
    //   _kdEpId = entity!.kdEpId!;
    // }
    // if(entity!.kdApi != null){
    //   _kdApi = entity!.kdApi!;
    // }
    if(entity!.analysisBook != null){
      _analysisBook.value = entity!.analysisBook!;
    }
    if(entity!.analysisReader != null){
      _analysisReader.value = entity!.analysisReader!;
    }
    if(entity!.exchange != null){
      _exchange.value = entity!.exchange!;
    }
    if(entity!.log != null){
      _log.value = entity!.log!;
    }
    if(entity!.action != null){
      _action.value = entity!.action!;
    }
    if(entity!.twoSided != null){
      twoSided.value = entity!.twoSided!;
    }
    if(entity!.main != null){
      main.value = entity!.main!;
    }
    // if(entity!.face != null){
    //   _face.value = entity!.face!;
    // }
    if(entity!.norms != null){
      _norms.value = entity!.norms!;
    }
    if(entity!.roomName != null){
      _roomName = entity!.roomName!;
    }
    // if(entity!.ledRule != null){
    //   _ledRule.value = entity!.ledRule!;
    // }
    if(entity!.psw != null){
      _psw = entity!.psw!;
    }
    if(entity!.roomNo != null){
      _roomNo = entity!.roomNo!;
    }
    if(entity!.columnNo != null){
      _columnNo = entity!.columnNo!;
    }
    if(entity!.deviceName != null){
      _deviceName = entity!.deviceName!;
    }
    if(entity!.idSerial != null){
      _idSerial.value = entity!.idSerial!;
    }
    if(entity!.hfSerial != null){
      _hfSerial.value = entity!.hfSerial!;
    }
    if(entity!.hfBaudRate != null){
      _hfBaudRate.value = entity!.hfBaudRate!;
    }

    if(entity!.auth != null){
      _auth = entity!.auth!;
    }
    if(entity!.sleepTime != null){
      _sleepTime = entity!.sleepTime!;
    }
    if(entity!.rotate != null){
      _rotate = entity!.rotate!;
    }
    if(entity!.actionTime != null){
      _actionTime = entity!.actionTime!;
    }
    if(entity!.inventoryTime != null){
      _inventoryTime = entity!.inventoryTime!;
    }
    if(entity!.reader != null){
      _readerList.clear();
      _readerList.addAll(entity!.reader!);
    }
    if(entity!.place != null){
      _placeList.clear();
      _placeList.addAll(entity!.place!);
    }
  }

  @override
  void dispose() {
    actionSubscription?.cancel();
    actionSubscription = null;
    super.dispose();
  }


  _apiWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  服务器地址 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 110.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _apiAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _apiAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _apiAddr.length))
            )),
          ),
        ),

        Text("  sip2参数 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 120.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _deviceNo = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceNo,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceNo.length))
            )),
          ),
        ),
      ],
    );
  }

  _serialWidget(){
    List<String> availablePorts = SerialPort.availablePorts;
    var items = availablePorts.map((e) => DropdownMenuItem(value:e, child:Text(e))).toList();
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  三合一读卡器  ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _idSerial.value,
            onChanged: (value){
              _idSerial.value = value.toString();
            },
            items: items,
          )),
        ),
        Text("  hf读卡器  ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _hfSerial.value,
            onChanged: (value){
              _hfSerial.value = value.toString();
            },
            items: items,
          )),
        ),
        Text("  hf波特率  ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _hfBaudRate.value,
            onChanged: (value){
              _hfBaudRate.value = value.toString();
            },
            items: _baudRatedRules,
          )),
        ),
      ],
    );
  }

  _ruleWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  条码号解析规则 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _analysisBook.value,
            onChanged: (value){
              _analysisBook.value = value.toString();
            },
            items: _analysisBookRules,
          )),
        ),
        Text("  读者卡解析规则 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _analysisReader.value,
            onChanged: (value){
              _analysisReader.value = value.toString();
            },
            items: _analysisReaderRules,
          )),
        ),

        Text("  书架规格 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _norms.value,
            onChanged: (value){
              _norms.value = value.toString();
            },
            items: _normsRules,
          )),
        ),
      ],
    );
  }

  _placeInfoWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  馆名 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 70.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _roomName = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _roomName.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _roomName.toString().length))
            )),
          ),
        ),
        Text("  馆号 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 30.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _roomNo = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _roomNo.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _roomNo.toString().length))
            )),
          ),
        ),
        Text("  列号 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 40.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _columnNo = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _columnNo.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _columnNo.toString().length))
            )),
          ),
        ),
        TextButton(onPressed: () {
          if(_columnNo.isEmpty || _roomNo.isEmpty){
            return;
          }
          for (var element in _placeList) {
            element.place = _roomNo.padLeft(2,'0') + _columnNo.padLeft(4,'0') + element.place!.substring(6,12);
            element.placeName = _analyzePlace(_roomNo.padLeft(2,'0') + _columnNo.padLeft(4,'0') + element.place!.substring(6,12));
            _saveReader();
          }
          toastWarn('更新存址成功');
          setState(() {

          });
        }, child: Text('更新存址', style: TextStyle(fontSize: 8.sp))),

      ],
    );
  }

  _actionWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text('  借还关', style: TextStyle(fontSize: 8.sp),),
        Obx(() => Switch(
            value: _action.value,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            onChanged: (value) {
              _action.value = !_action.value;
            }
        )),
        Text('借还开', style: TextStyle(fontSize: 8.sp),),
        Text("  管理员密码",   style: TextStyle(fontSize: 8.sp)),
        Container(
          width: 60.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _psw = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _psw,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _psw.length))
            )),
          ),
        ),

        Text("  调试日志",style: TextStyle(fontSize: 8.sp),),
        Obx(() => Checkbox(
            side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) {
              return const BorderSide(width: 2);
            }),
            value: _log.value,
            onChanged: (value){
              _log.value = !_log.value;
            }
        )),
      ],
    );
  }

  _deviceNameWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  设备名",   style: TextStyle(fontSize: 8.sp)),
        Container(
          width: 80.w,
          height: 20.h,
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _deviceName = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceName,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceName.length))
            )),
          ),
        ),
        TextButton(onPressed: () {
          _saveDevice();
        }, child: Text('保存配置', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          _saveDevice();
          setting(_deviceNo.replaceAll('device_id=', ''),entity!);
        }, child: Text('上传配置', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () async {
          var data = await getSetting(_deviceNo.replaceAll('device_id=', ''));
          if(data !=null){
            entity = SettingEntity.fromJson(data);
            setState(() {
              _init();
            });
          }

        }, child: Text('下载配置', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          Get.defaultDialog(
            title: '清除缓存',
            titleStyle: TextStyle(
              color: const Color(0xFF000000),
              fontSize: 10.sp,
            ),
            middleText: '确定清除缓存？',
            middleTextStyle: TextStyle(
              color: const Color(0xFF000000),
              fontSize: 8.sp,
            ),
            radius: 4.sp,
            textConfirm: '确定',
            // textCancel: '取消',
            confirmTextColor: const Color(0xFF007AFF),
            backgroundColor: const Color(0xD1F8F8F8),
            buttonColor: Colors.transparent,
            onConfirm: () {
              var storage = GetStorage('uid_no');
              storage.erase();
              Get.back();
            },
          );
        }, child: Text('清除缓存', style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          Get.to(()=>const Log());
        }, child: Text('查看日志', style: TextStyle(fontSize: 8.sp))),
      ],
    );
  }

  _authWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  认证方式(1=读者卡,2=身份证,3=人脸,4=二维码)",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 40.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _auth = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _auth,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _auth.length))
            )),
          ),
        ),
        Text("  摄像头翻转(1-4)",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 20.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _rotate = int.tryParse(value)??2;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _rotate.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _rotate.toString().length))
            )),
          ),
        ),
        Text("    AB面对换",style: TextStyle(fontSize: 8.sp),),
        Obx(() => Checkbox(
            side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) {
              return const BorderSide(width: 2);
            }),
            value: _exchange.value,
            onChanged: (value){
              _exchange.value = !_exchange.value;
            }
        )),
      ],
    );
  }

  _saveDevice(){
    // entity!.kdApi = _kdApi;
    // entity!.kdEpId = _kdEpId;
    // entity!.kdAppSecret = _kdAppSecret;
    // entity!.kdAppId = _kdAppId;
    entity!.deviceName = _deviceName;
    entity!.apiAddr = _apiAddr;
    entity!.deviceNo = _deviceNo;
    entity!.roomName = _roomName;
    entity!.log = _log.value;
    entity!.psw = _psw;
    entity!.roomNo = _roomNo;
    entity!.columnNo = _columnNo;
    entity!.idSerial = _idSerial.value;
    entity!.hfSerial = _hfSerial.value;
    entity!.hfBaudRate = _hfBaudRate.value;
    entity!.analysisBook = _analysisBook.value;
    entity!.analysisReader = _analysisReader.value;
    entity!.exchange = _exchange.value;
    entity!.action = _action.value;
    // entity!.face = _face.value;
    // entity!.ledRule = _ledRule.value;
    entity!.reader = _readerList;
    entity!.place = _placeList;
    entity!.auth = _auth;
    entity!.twoSided = twoSided.value;
    entity!.main = main.value;
    entity!.norms = _norms.value;
    entity!.rotate = _rotate;
    entity!.actionTime = _actionTime;
    entity!.sleepTime = _sleepTime;
    entity!.inventoryTime = _inventoryTime;
    box.write('setting_entity', entity!.toJson());
    toastWarn('保存成功');

  }

  _saveReader(){
    entity!.reader = _readerList;
    entity!.place = _placeList;
    box.write('setting_entity', entity!.toJson());
  }
  _savePlace(){
    entity!.place = _placeList;
    box.write('setting_entity', entity!.toJson());
  }

  _deleteReader(){
    _readerList.clear();
    _placeList.clear();
    entity!.reader = _readerList;
    entity!.place = _placeList;
    box.write('setting_entity', entity!.toJson());
  }

  _usefulReader(index,state){
    var reader = _readerList[index];
    _readerList.removeAt(index);
    reader.state = state;
    _readerList.insert(index, reader);
    entity!.reader = _readerList;
    box.write('setting_entity', entity!.toJson());

  }

  var _count = 0;

  _addReaderDialog(){

    Get.defaultDialog(
      title: "",
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Container(
        width: 200.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(6.r)),
        ),
        alignment: Alignment.center,
        child: Column(
          children: [
            SizedBox(height: 10.h,),
            Text('添加读写器',style: TextStyle(fontSize: 8.sp),),
            SizedBox(height: 5.h,),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('读写器数量 ',style: TextStyle(fontSize: 8.sp),),
                SizedBox(
                  width: 50.w,
                  height: 20.h,
                  child:  TextField(
                    decoration:  InputDecoration(
                      border:  const OutlineInputBorder(),
                      contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
                    ),
                    style: TextStyle(fontSize: 8.sp),
                    onChanged: (value){
                      _count = int.tryParse(value)??0;
                    },
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(onPressed: () {

                  for(var i = 0;i<_count;i++){
                    // var knot = _readerList.isEmpty?1:_readerList.last.knot!+1;

                    _readerList.add(
                        SettingEntityReader()
                        // ..readerAddr = _addr.value
                        //   ..station = i+1
                          ..knot = i+1
                    );

                    var floor = 5;
                    if(_norms.value == '5层'){
                      floor = 5;
                    }
                    if(_norms.value == '6层'){
                      floor = 6;
                    }

                    for(var j = 1;j<= floor;j++){
                      _placeList.add(
                          SettingEntityPlace()
                            ..place = '${_roomNo.padLeft(2,'0')}${_columnNo.padLeft(4,'0')}${_exchange.value == false?'01':'02'}${(i+1).toString().padLeft(2,'0')}0$j'
                            ..placeName = _analyzePlace('${_roomNo.padLeft(2,'0')}${_columnNo.padLeft(4,'0')}${_exchange.value == false?'01':'02'}${(i+1).toString().padLeft(2,'0')}0$j')
                            ..knot = i+1
                            // ..broad = (i+1).toString()
                            ..ant = '${(i+1).toRadixString(16).toUpperCase().padLeft(2,'0')}${(j*2-1).toRadixString(16).toUpperCase().padLeft(2,'0')}'
                            // ..led = (j*2-1).toString()
                      );
                    }
                    for(var j = 1;j<= floor;j++){
                      _placeList.add(
                          SettingEntityPlace()
                            ..place = '${_roomNo.padLeft(2,'0')}${_columnNo.padLeft(4,'0')}${_exchange.value == false?'02':'01'}${(i+1).toString().padLeft(2,'0')}0$j'
                            ..placeName = _analyzePlace('${_roomNo.padLeft(2,'0')}${_columnNo.padLeft(4,'0')}${_exchange.value == false?'02':'01'}${(i+1).toString().padLeft(2,'0')}0$j')
                            ..knot = i+1
                            // ..broad = (i+1).toString()
                            ..ant = '${(i+1).toRadixString(16).toUpperCase().padLeft(2,'0')}${(j*2).toRadixString(16).toUpperCase().padLeft(2,'0')}'
                            // ..led = (j*2).toString()
                      );
                      _saveReader();
                    }
                  }


                  Get.back();
                }, child: const Text('确定')),
                TextButton(onPressed: () {
                  Get.back();
                }, child: const Text('取消', style: TextStyle(color: Colors.black),)),
              ],
            )
          ],
        ),
      ),
    );
  }


  _labelPlaceRow(List<SettingEntityPlace> thisList){
    return  Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _listCell("存址编号",width: 80),
        _listCell("存址名称",width: 120),
        _listCell("天线号",width: 80),
        // _listCell("灯控号",width: 40),
        // _listCell("板地址",width: 40),

        // InkWell(
        //   onTap: (){
        //     if(settingEntity.main??false){
        //       // BotToast.showLoading(clickClose: true);
        //       // hfSerialPortHelper.sendData(inventoryAll(station));
        //     }
        //   },
        //   child:  Text('  整列盘点 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
        // ),
      ],
    );
  }

  _listCell(text,{int width = 90, int height = 20, Color color =Colors.black }){
    return Container(
        alignment: Alignment.center,
        width: width.w,
        height: height.h,
        child: Text('$text',style: TextStyle(color:color, fontSize: 8.sp),textAlign: TextAlign.center,)
    );
  }

  _readerLabelRow(){
    return  Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        // _listCell("编号",width: 26),
        // _listCell("读写器地址",width: 80),
        _listCell("列号",width: 100),
        _listCell("状态",width: 100),
        InkWell(
          onTap: (){
            if(_readerList.isNotEmpty){
              toastWarn('请先删除当前读写器');
              return;
            }
            _addReaderDialog();
          },
          child: Text('  新增读写器', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
        ),
        SizedBox(width: 20.w,),
        InkWell(
          onTap: (){
            Get.defaultDialog(
              title: '删除读写器',
              titleStyle: TextStyle(
                color: const Color(0xFF000000),
                fontSize: 8.sp,
              ),
              middleText: '确定删除？',
              middleTextStyle: TextStyle(
                color: const Color(0xFF000000),
                fontSize: 8.sp,
              ),
              radius: 8.sp,
              textConfirm: '确定',
              // textCancel: '取消',
              confirmTextColor: const Color(0xFF007AFF),
              backgroundColor: const Color(0xD1F8F8F8),
              buttonColor: Colors.transparent,
              onConfirm: () {
                _deleteReader();
                Get.back();
              },
            );
          },
          child: Text(' 删除读写器 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
        ),
        // SizedBox(width: 20.w,),
        // InkWell(
        //   onTap: (){
        //     Get.off(()=>const Test());
        //   },
        //   child:  Text(' 测试模式 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
        // ),
      ],
    );
  }


  _readerItemWidget(index) {
    var item = _readerList[index];
    // var visible = false.obs;
    var thisList = _placeList.where((element) => element.knot == item.knot).toList();
    return Obx(() => Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _listCell('${item.knot.toString().padLeft(2,"0")}节',width: 100),
            // _listCell('${item.readerAddr}',width: 80),
            // _listCell(item.station.toString().padLeft(2,'0'),width: 100),
            Container(
              alignment: Alignment.center,
              width: 100.w,
              height: 10.h,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('禁用', style: TextStyle(fontSize: 8.sp),),
                  Switch(
                      value: item.state == 0,
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      onChanged: (value) {
                        if( item.state == 0){
                          item.state = 1;
                        }else{
                          item.state = 0;
                        }
                        _usefulReader(index,item.state);

                      }
                  ),
                  Text('启用', style: TextStyle(fontSize: 8.sp),),
                ],
              ),
            ),
            SizedBox(width: 10.w,),
            InkWell(
              onTap: (){
                item.visible.value = !item.visible.value;
              },
              child:  Text(' 配置 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
            ),
          ],
        ),
        if(item.visible.value)...[
          _line(),
          _labelPlaceRow(thisList),
          _line(),
          ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              return _placeItemWidget(thisList[index]);
            },
            separatorBuilder: (BuildContext context, int index) {
              return const Divider(height: 1.0, color: Colors.grey);
            },
            shrinkWrap: true,
            physics: const ClampingScrollPhysics(),
            itemCount:  thisList.length,
          )
        ]
      ],
    ));
  }

  _editPlaceDialog(SettingEntityPlace item){
    var ant = item.ant!;
    // var led = item.led!;
    // var broad = item.broad!;
    Get.defaultDialog(
      title: "",
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Container(
        width: 200.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(6.r)),
        ),
        alignment: Alignment.center,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(height: 10.h,),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('天线号   ',style: TextStyle(fontSize: 8.sp),),
                SizedBox(
                  width: 50.w,
                  height: 20.h,
                  child: TextField(
                    decoration:  InputDecoration(
                      border:  const OutlineInputBorder(),
                      contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
                    ),
                    style: TextStyle(fontSize: 8.sp),
                    onChanged: (value){
                      ant = value;
                    },
                    controller: TextEditingController.fromValue(TextEditingValue(
                        text: item.ant!,
                        selection: TextSelection.fromPosition(
                            TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: item.ant!.length))
                    )),
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(onPressed: () {

                  if(ant.isEmpty){
                    toastWarn('数据不能为空');
                    return;
                  }

                  var index = _placeList.indexOf(item);
                  _placeList.remove(item);
                  item.ant = ant;
                  // item.led = led;
                  // item.broad = broad;
                  _placeList.insert(index, item);

                  setState(() {
                    _savePlace();
                  });
                  Get.back();
                }, child: const Text('确定')),
                TextButton(onPressed: () {
                  Get.back();
                }, child: const Text('取消', style: TextStyle(color: Colors.black),)),
              ],
            )
          ],
        ),
      ),
    );
  }
  _placeItemWidget(SettingEntityPlace item) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        _listCell('${item.place}',width: 80),
        _listCell('${_analyzePlace(item.place!)}',width: 120),
        _listCell(item.ant,width: 80),
        InkWell(
          onTap: () async {
            if(settingEntity.main??false){
              var data = await openLight(item.ant!);
              hfSerialPortHelper.sendData(data);
              toastWarn('灯已闪烁');
            }
          },
          child: Text(' 闪灯 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
        ),
        // InkWell(
        //   onTap: () async {
        //     if(settingEntity.main??false){
        //       var data = await closeLight(item.ant!);
        //       hfSerialPortHelper.sendData(data);
        //     }
        //   },
        //   child: Text(' 关灯 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
        // ),
        SizedBox(width: 20.w,),
        InkWell(
          onTap: () async {
            if(settingEntity.main??false){
              BotToast.showLoading(clickClose: true);
              var data = await inventoryWithAnt([item.ant!]);
              hfSerialPortHelper.sendData(data);
            }
          },
          child:  Text(' 盘点 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
        ),
      ],
    );
  }

  _analyzePlace(String place){
    // String room = place.substring(0,2);
    // String column = place.substring(2,6);
    String side = place.substring(6,8);
    String knot = place.substring(8,10);
    String floor = place.substring(10,12);
    return '${side=='01'?'A面':'B面'}$knot节$floor层';
  }

  _line(){
    return const Divider(height: 1.0,color: Colors.grey,);
  }

  _timeWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  熄屏时间",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 30.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _sleepTime = int.tryParse(value)!;
              }
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _sleepTime.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _sleepTime.toString().length))
            )),
          ),
        ),
        Text(" 页面停留时间 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 30.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _actionTime = int.tryParse(value)!;
              }
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _actionTime.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _actionTime.toString().length))
            )),
          ),
        ),
        Text(" 盘点时间 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 30.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _inventoryTime = int.tryParse(value)!;
              }
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _inventoryTime.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _inventoryTime.toString().length))
            )),
          ),
        ),
        Text('   单面', style: TextStyle(fontSize: 8.sp),),
        Obx(() => Switch(
            value: twoSided.value,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            onChanged: (value) {
              twoSided.value = !twoSided.value;
            }
        )),
        Text('双面', style: TextStyle(fontSize: 8.sp),),
        Text('   副屏', style: TextStyle(fontSize: 8.sp),),
        Obx(() => Switch(
            value: main.value,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            onChanged: (value) {
              main.value = !main.value;
            }
        )),
        Text('主屏', style: TextStyle(fontSize: 8.sp),),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child:Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text("配置"),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: (){
              if(box.hasData('setting_entity')){
                settingEntity = SettingEntity.fromJson(box.read("setting_entity"));
              }
              Get.back();
            },
          ),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _deviceNameWidget(),
            _apiWidget(),
            _serialWidget(),
            _ruleWidget(),
            _timeWidget(),
            _authWidget(),
            _placeInfoWidget(),
            _actionWidget(),
            // _faceWidget(),
            // _faceWidget2(),
            SizedBox(height: 10.h,),
            _line(),
            _readerLabelRow(),
            _line(),
            Obx(() => Expanded(
                child: ListView.separated(
                  itemBuilder: (BuildContext context, int index) {
                    return _readerItemWidget(index);
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return const Divider(height: 1.0, color: Colors.grey);
                  },
                  itemCount:  _readerList.length,
                )
            )),
          ],
        )
      ),
    );
  }
}

